/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TFrame.java
 *
 * Created on Mar 26, 2012, 6:27:58 PM
 */
package nac.tbot;

import java.awt.*;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

/**
 *
 * @author DTIT
 */
public class TFrame1 extends javax.swing.JFrame {

  private boolean findingBoard = false;
  private Timer timer;
  private Robot robot = null;

  /**
   * Creates new form TFrame
   */
  public TFrame1() {
    initComponents();
    try {
      robot = new Robot();
    } catch (AWTException ex) {
      Logger.getLogger(TFrame1.class.getName()).log(Level.SEVERE, null, ex);
    }
    tPanel2.setDelayTextField(jTextField2);
    tPanel2.setTowerGapTextField(jTextField3);
    tPanel2.setBuildLimitTextField(jTextField4);
    tPanel2.setBreakLimitTextField(jTextField5);

    timer = new Timer(30, new ActionListener() {

      @Override
      public void actionPerformed(ActionEvent e) {
        tPanel2.repaint();
      }
    });

    Toolkit.getDefaultToolkit().addAWTEventListener(new AWTFocusListener(), AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK);
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    findBoardButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    tPanel2 = new nac.tbot.TPanel();
    jTextField2 = new javax.swing.JTextField();
    jTextField3 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    jTextField4 = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jTextField5 = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    addWindowFocusListener(new java.awt.event.WindowFocusListener() {
      public void windowGainedFocus(java.awt.event.WindowEvent evt) {
        formWindowGainedFocus(evt);
      }
      public void windowLostFocus(java.awt.event.WindowEvent evt) {
        formWindowLostFocus(evt);
      }
    });

    findBoardButton.setText("Find Board");
    findBoardButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        findBoardButtonActionPerformed(evt);
      }
    });

    jLabel1.setText("Key Delay:");

    tPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

    javax.swing.GroupLayout tPanel2Layout = new javax.swing.GroupLayout(tPanel2);
    tPanel2.setLayout(tPanel2Layout);
    tPanel2Layout.setHorizontalGroup(
      tPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 178, Short.MAX_VALUE)
    );
    tPanel2Layout.setVerticalGroup(
      tPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 358, Short.MAX_VALUE)
    );

    jTextField2.setText("42");

    jTextField3.setText("2");

    jLabel2.setText("Tower Gap:");

    jTextField4.setText("15");

    jLabel3.setText("Buildup Limit:");

    jTextField5.setText("5");

    jLabel4.setText("Breakdown Limit:");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addComponent(tPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jLabel2)
              .addComponent(jLabel3))
            .addGap(37, 37, 37)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
              .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 43, Short.MAX_VALUE)
              .addComponent(jTextField4)))
          .addComponent(findBoardButton)
          .addGroup(layout.createSequentialGroup()
            .addGap(39, 39, 39)
            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(layout.createSequentialGroup()
            .addComponent(jLabel4)
            .addGap(18, 18, 18)
            .addComponent(jTextField5)))
        .addContainerGap(58, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(tPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(layout.createSequentialGroup()
            .addComponent(findBoardButton)
            .addGap(65, 65, 65)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jLabel1)
              .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jLabel2)
              .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jLabel3)
              .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(jLabel4)
              .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(43, 43, 43)
            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void findBoardButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_findBoardButtonActionPerformed

    if (findingBoard == false) {
      timer.stop();
      findingBoard = true;
      findBoardButton.setText("Click inside board...");
    }
  }//GEN-LAST:event_findBoardButtonActionPerformed

  private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus
//    timer.stop();
  }//GEN-LAST:event_formWindowLostFocus

  private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
//     timer.start();
  }//GEN-LAST:event_formWindowGainedFocus

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(TFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(TFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(TFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(TFrame1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

      @Override
      public void run() {
        new TFrame1().setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton findBoardButton;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JTextField jTextField2;
  private javax.swing.JTextField jTextField3;
  private javax.swing.JTextField jTextField4;
  private javax.swing.JTextField jTextField5;
  private nac.tbot.TPanel tPanel2;
  // End of variables declaration//GEN-END:variables

  private class AWTFocusListener implements AWTEventListener {

    @Override
    public void eventDispatched(AWTEvent event) {
      if (event.getID() == FocusEvent.FOCUS_LAST) {
        if (findingBoard) {
          SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
              findBorders();
            }
          });

        }
      }
    }
  }

  private void findBorders() {
    findBoardButton.setText("Finding...");
    Point initialPoint = MouseInfo.getPointerInfo().getLocation();
    int ix = initialPoint.x;
    int iy = initialPoint.y;
    int x = 0;
    int y = 0;
    Color color;
    int blackCount = 0;

    while (ix > 0) {

      color = robot.getPixelColor(ix, iy);

      if (color.equals(Color.BLACK)) {
        blackCount++;
      } else {
        blackCount = 0;
      }
      if (blackCount == 6) {
        x = ix;
        break;
      }
      ix--;
    }

    ix = initialPoint.x;
    iy = initialPoint.y;
    blackCount = 0;
    while (iy > 0) {

      color = robot.getPixelColor(ix, iy);

      if (color.equals(Color.BLACK)) {
        blackCount++;
      } else {
        blackCount = 0;
      }
      if (blackCount == 6) {
        y = iy;
        break;
      }
      iy--;
    }
    findingBoard = false;
    tPanel2.setLoc(new Point(x + 6, y + 8));
    timer.start();
    findBoardButton.setText("Find board");
  }
}
